import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Route, Redirect } from 'react-router'
import { global as userDuck } from 'ducks'

const createRedirect = ({ location }) => ({
  pathname: '/auth',
  state: {
    returnURL: location.pathname,
  },
})

const createRedirectHome = ({ location }) => ({
  pathname: '/',
  state: {
    returnURL: location.pathname,
  },
})

const AuthedRoute = ({
  component: Component, isAuthed, isSignedIn, path, ...rest
}) => {
  let render
  if (isAuthed && !isSignedIn) {
    render = props => <Component {...props} />
  } else if (isAuthed && isSignedIn) {
    render = props => <Redirect path={path} to={createRedirectHome(props)} />
  } else {
    render = props => <Redirect path={path} to={createRedirect(props)} />
  }
  return <Route {...rest} render={render} />
}

AuthedRoute.propTypes = {
  component: PropTypes.func.isRequired,
  isSignedIn: PropTypes.bool.isRequired,
}

const mapStateToProps = state => ({
  isAuthed: userDuck.selectors.isAuthed(state),
  isSignedIn: userDuck.selectors.isSignedIn(state),
})

export default connect(mapStateToProps)(AuthedRoute)
